package cn.tedu.egweibo01.controller;

import cn.tedu.egweibo01.mapper.UserMapper;
import cn.tedu.egweibo01.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo01.pojo.dto.UserRegDTO;
import cn.tedu.egweibo01.pojo.entity.User;
import cn.tedu.egweibo01.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/users")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("reg")
    public int reg(@RequestBody UserRegDTO userRegDTO) {
        if (userMapper.selectUserByUsername(userRegDTO.getUsername()) == null) {
            User user = new User();
            BeanUtils.copyProperties(userRegDTO, user);
            user.setCreated(new Date());
            return userMapper.insertUser(user); // 1 注册成功
        }
        return 2; //用户已存在
    }

    @PostMapping("login")
    public int login(@RequestBody UserLoginDTO userLoginDTO, HttpSession session){
        UserVO userVO = userMapper.selectUserByUsername(userLoginDTO.getUsername());
        if(userVO!=null){
            if(userVO.getPassword().equals(userLoginDTO.getPassword())){
                session.setAttribute("user",userVO);
                return 1; // 登陆成功
            }return 2; // 用户名或密码错误
        }return 3; // 用户名错误
    }

    @GetMapping("currentUser")
    public UserVO currentUser(HttpSession session){
        return (UserVO) session.getAttribute("user");
    }

    @GetMapping("logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }

}
